#!/bin/bash

 git submodule add https://github.com/uNetworking/uWebSockets.git uWebSockets
 
 cd uWebSockets
 
 git submodule update --init --recursive

# 修改 uSockets/Makefile
sed -i 's/override CFLAGS += -DLIBUS_USE_OPENSSL/override CFLAGS += -DLIBUS_USE_OPENSSL -fPIC/g' uSockets/Makefile
sed -i 's/\$(CXX) \$(CXXFLAGS) -std=c++17 -flto -O3 -c src\/crypto\/\*.cpp/\$(CXX) \$(CXXFLAGS) -std=c++17 -fPIC -flto -O3 -c src\/crypto\/\*.cpp/g' uSockets/Makefile

cd ..
# Make 编译 uWebsockets 库
make

TARGET_DIR="uweb_server_shared"  # 需要拷贝文件的目录
DEST_DIR="uweb_server_demo"
LIB_DEST_DIR="$DEST_DIR/lib"
INCLUDE_DEST_DIR="$DEST_DIR/include"

# 确保目标目录存在
if [ ! -d "$LIB_DEST_DIR" ]; then
    mkdir -p "$LIB_DEST_DIR"
fi
if [ ! -d "$INCLUDE_DEST_DIR" ]; then
    mkdir -p "$INCLUDE_DEST_DIR"
fi

# Debug 信息
echo "Copying libuweb_server.so from ./$TARGET_DIR/libuweb_server.so to ./$LIB_DEST_DIR/"
echo "Copying header files from ./$TARGET_DIR/*.h to ./$INCLUDE_DEST_DIR/"

# 拷贝文件
cp "./$TARGET_DIR/libuweb_server.so" "./$LIB_DEST_DIR/"
if [ $? -ne 0 ]; then
    echo "Failed to copy libuweb_server.so"
    exit 1
fi

cp ./$TARGET_DIR/*.h "./$INCLUDE_DEST_DIR/"
if [ $? -ne 0 ]; then
    echo "Failed to copy header files"
    exit 1
fi

# 编译 demo
cd "$DEST_DIR"

BUILD_DIR="build"

# 创建 build 目录
if [ ! -d "$BUILD_DIR" ]; then
    mkdir "$BUILD_DIR"
fi

cd "$BUILD_DIR"
# 运行 cmake ..
cmake ..

# 检查 cmake 是否成功
if [ $? -ne 0 ]; then
    echo "CMake configuration failed"
    exit 1
fi

# 执行 make
make

# 检查 make 是否成功
if [ $? -ne 0 ]; then
    echo "Build failed"
    exit 1
fi

echo "Build and copy completed successfully"
